import React, { Component } from 'react';
import { connect } from 'dva';
import Ellipsis from '@/components/Ellipsis';
import { maxLength } from '@/utils/form';
import { REGION_ADDRESS_TYPE, REGION_TYPE, SERVICE_STATUS } from '@/Constants';
import { NAME_RULE, CODE_RULE } from '@/Constants/rules';
import {
  Menu,
  Dropdown,
  Button,
  Icon,
  message,
  Card,
  Form,
  Modal,
  Input,
  Tree,
  Transfer,
  Switch,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import MyIcon from '@/components/MyIcon';
import { trim, treeIcon } from '@/utils/utils';
import styles from './Add.less';
import Content from './Content';
import api from '@/api';

const FormItem = Form.Item;
const { TreeNode } = Tree;

@connect(({ usergroups, org }) => ({
  sysRoots: usergroups.sysRoots,
  userGroupsMenuList: usergroups.userGroupsMenuList,
  orgUsers: org.orgUsers,
}))
@Form.create()
class Add extends Component {
  state = {
    expandedKeys: [],
    autoExpandParent: true,
    selectedKeys: [],
    transferSelectedKeys: [],
    transferData: [],
  };

  componentDidMount() {
    let searchIptList = this.transfer
      ? this.transfer.querySelectorAll('.ant-transfer-list-search')
      : [];
    searchIptList.forEach(searchIpt => {
      searchIpt && (searchIpt.maxLength = 30);
    });
  }

  componentWillReceiveProps(nextProps) {
    const { orgTree } = nextProps;
    if (this.props.orgTree !== orgTree) {
      orgTree &&
        this.setState({
          expandedKeys: orgTree[0] ? [orgTree[0].id] : [],
        });
    }
  }

  fetchOrgUsers = orgId => {
    return this.props.dispatch({
      type: 'org/fetchOrgAllUsers',
      payload: {
        pathParams: {
          id: orgId,
        },
      },
    });
  };

  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  onSelect = async (selectedKeys, info) => {
    this.setState({ selectedKeys });
    await this.fetchOrgUsers(selectedKeys[0]);
    const { transferData } = this.state;
    const { orgUsers, targetKeys } = this.props;
    let targetData = transferData.filter(user => targetKeys.includes(user.id));
    let users = orgUsers.concat(
      targetData.filter(user => !orgUsers.map(item => item.id).includes(user.id))
    );
    this.setState({
      transferData: users,
    });
  };

  renderNodeTitle = item => {
    const icon = treeIcon(item);
    return (
      <span>
        <MyIcon className={styles.myIcon} type={icon} />
        <span>{item.shortName}</span>
      </span>
    );
  };

  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={this.renderNodeTitle(item)} key={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={this.renderNodeTitle(item)} key={item.id} dataRef={item} />;
    });
  };

  renderTree = () => {
    const { orgTree } = this.props;
    return (
      <Tree
        onExpand={this.onExpand}
        expandedKeys={this.state.expandedKeys}
        autoExpandParent={this.state.autoExpandParent}
        onSelect={this.onSelect}
        selectedKeys={this.state.selectedKeys}
      >
        {this.renderTreeNodes(orgTree)}
      </Tree>
    );
  };

  filterOption = (inputValue, option) => {
    let str = option.fullName || '';
    str = str + (option.userName || '');
    return str.indexOf((inputValue || '').trim()) > -1;
  };

  handleChange = (targetKeys, direction, moveKeys) => {
    this.props.onTargetChange && this.props.onTargetChange(targetKeys);
    if (direction === 'left') {
      const { transferData } = this.state;
      const { orgUsers } = this.props;

      let orgUsersId = orgUsers.map(user => user.id);
      let outCurrentOrgUsers = moveKeys.filter(id => !orgUsersId.includes(id));
      this.setState({
        transferData: transferData.filter(user => !outCurrentOrgUsers.includes(user.id)),
      });
    }
  };

  handleSearch = (dir, value) => {
    console.log('search:', dir, value);
  };

  handleTransferSelectedKeysChange = (sourceSelectedKeys, targetSelectedKeys) => {
    this.setState({ transferSelectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
  };

  renderTransferList = item => {
    return (
      <Ellipsis tooltip length={15}>
        {`${item.fullName}(${item.userName})`}
      </Ellipsis>
    );
  };

  renderTransfer = () => {
    return (
      <div
        ref={transfer => {
          this.transfer = transfer;
        }}
      >
        <Transfer
          listStyle={{
            width: 260,
            height: 443,
          }}
          locale={{
            searchPlaceholder: '请输入姓名或账号查询',
          }}
          dataSource={this.state.transferData}
          rowKey={record => record.id}
          showSearch
          filterOption={this.filterOption}
          targetKeys={this.props.targetKeys}
          selectedKeys={this.state.transferSelectedKeys}
          onSelectChange={this.handleTransferSelectedKeysChange}
          onChange={this.handleChange}
          onSearch={this.handleSearch}
          render={this.renderTransferList}
        />
      </div>
    );
  };

  render() {
    return (
      <div className={styles.addUsers}>
        <Card className={styles.tree} bordered={false}>
          {this.renderTree()}
        </Card>
        <Card className={styles.transfer} bordered={false}>
          {this.renderTransfer()}
        </Card>
      </div>
    );
  }
}

export default Add;
